<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Common;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    /**
     * 处理认证尝试
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        //$credentials = $request->only('name', 'password'); // name、password 是表单传的字段
        $credentials = [
            'email' => $request->input('name'),
            'password' => $request->input('password'),
            //'status' => 1
        ];
        if (Auth::guard('admin')->attempt($credentials)) {
            // 认证通过
            $admin = Auth::guard('admin')->user();
            $id = $admin->id;
            // 记录登录时间及ip
            $data['last_login_time'] = time();
            $data['last_login_ip'] = get_IP();
            $record = \App\Models\Admin::where('id', $id)->update($data);
            // 日志
            $logRes = Common::actionLog(request(), $id, '管理员登录', 0, json_encode([$admin]));

            //return redirect()->intended('index');
            return response()->json([
                'code' => 1,
                'msg' => '登录成功'
            ]);
        }

        return response()->json([
            'code' => 0,
            'msg' => '用户名或密码错误',
        ]);
    }

    /**
     * 登录
     */
    public function login(Request $request)
    {
        if (Auth::guard('admin')->user()) {
            return redirect(route('admin.index'));
        }

        return view('admin.auth.login');
    }

    /**
     * 退出
     */
    public function logout(Request $request)
    {
        // 清除缓存
        Cache::forget('admin_menu');

        Auth::guard('admin')->logout();

        return redirect(route('admin.login'));
    }
}
